#include "postgres.h"

#include "fmgr.h"
#include "ltree/ltree.h"
#include "plpython.h"

PG_MODULE_MAGIC;

extern void _PG_init(void);

/* 链接到plpython模块中的函数 */
typedef PyObject *(*PLyUnicode_FromStringAndSize_t) (const char *s, Py_ssize_t size);
static PLyUnicode_FromStringAndSize_t PLyUnicode_FromStringAndSize_p;


/*
 * 模块初始化函数：获取跨模块调用的函数指针。
 */
void _PG_init(void)
{
	/* 断言验证上述 typedef 与原始声明匹配 */
	AssertVariableIsOfType(&PLyUnicode_FromStringAndSize, PLyUnicode_FromStringAndSize_t);
	PLyUnicode_FromStringAndSize_p = (PLyUnicode_FromStringAndSize_t)
		load_external_function("$libdir/" PLPYTHON_LIBNAME, "PLyUnicode_FromStringAndSize",
							   true, NULL);
}


/* 这些定义必须在模块初始化函数之后 */
#define PLyUnicode_FromStringAndSize PLyUnicode_FromStringAndSize_p


PG_FUNCTION_INFO_V1(ltree_to_plpython);

Datum ltree_to_plpython(PG_FUNCTION_ARGS)
{
	ltree	   *fc_in = PG_GETARG_LTREE_P(0);
	int			fc_i;
	PyObject   *fc_list;
	ltree_level *fc_curlevel;

	fc_list = PyList_New(fc_in->numlevel);
	if (!fc_list)
		ereport(ERROR,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory")));

	fc_curlevel = LTREE_FIRST(fc_in);
	for (fc_i = 0; fc_i < fc_in->numlevel; fc_i++)
	{
		PyList_SetItem(fc_list, fc_i, PLyUnicode_FromStringAndSize(fc_curlevel->name, fc_curlevel->len));
		fc_curlevel = LEVEL_NEXT(fc_curlevel);
	}

	PG_FREE_IF_COPY(fc_in, 0);

	return PointerGetDatum(fc_list);
}
